<template>
    <el-dialog v-model="dialogVisible" title="员工" width="30%" style="min-width: 300px;
    max-width: 500px;
    " draggable>

        <el-form label-width="80px">

            <el-row :gutter="20">

                <el-col :span="24">
                    <el-form-item label="* 门店" prop="goodsStoreId">
                        <el-button v-if="isShowSelectGoodsStore" @click="goodsStoreSelect.open()">{{ goodsStore.name
                        }}</el-button>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="* 姓名" prop="name">
                        <el-input size="large" placeholder="姓名" clearable v-model="requestParam.name"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="* 手机号" prop="phone">
                        <el-input size="large" placeholder="手机号" clearable v-model="requestParam.phone"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="邮箱" prop="email">
                        <el-input size="large" placeholder="邮箱" clearable v-model="requestParam.email"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="身份证号" prop="idCard">
                        <el-input size="large" placeholder="身份证号" clearable v-model="requestParam.idCard"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="地址" prop="address">
                        <el-input size="large" placeholder="地址" clearable v-model="requestParam.address"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>


                <el-col :span="24">
                    <el-form-item label="用户名">
                        <el-input size="large" placeholder="用户名" clearable v-model="requestParam.username" autocomplete="off"
                            :disabled="!isShowPasswordInput"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="24" v-if="isShowPasswordInput">
                    <el-form-item label="密码">
                        <el-input size="large" placeholder="密码" type="password" v-model="requestParam.password"
                            autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="24"
                v-show="requestParam.username!=null && requestParam.username!=''"
                >
                    <el-form-item label="角色" prop="remark">
                    <RoleSelect
                    ref="roleSelect"
                    @select="selectRole"
                    ></RoleSelect>
                    </el-form-item>
                </el-col>



            </el-row>

        </el-form>

        <template v-slot:footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit()">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>

    <GoodsStoreSelect ref="goodsStoreSelect" @select="goodsStoreSelectSelect"></GoodsStoreSelect>
</template>


<script lang="ts" setup>
import { ref, defineEmits, defineExpose, watch } from 'vue';
let dialogVisible = ref(false);
import $kt from '@/vueKantboot';
import { ElLoading, ElMessage } from 'element-plus'
import { de, fa } from 'element-plus/es/locale';
import GoodsStoreSelect from '@/components/goodsStoreSelect/goodsStoreSelect.vue';
import RoleSelect from '@/components/roleSelect/roleSelect.vue';



// 获取属性传参 isShowSelectGoodsStore
let props = defineProps({
    isShowSelectGoodsStore: {
        type: Boolean,
        default: false,
    }
});

let roleSelect = ref();

let roleCodes=ref([]);
let selectRole = (param: any) => {
    roleCodes.value=param;
}

let isShowSelectGoodsStore = ref(props.isShowSelectGoodsStore);

let goodsStoreSelect = ref();

let goodsStore = ref({
    id: null,
    name: "所有门店",
});

// emits
let emits = defineEmits(['submit']);

let requestParamStart = {
    "id": null,
    "name": null,
    "username": null,
    "phone": null,
    "email": null,
    "address": "",
    "idCard": null,
    "password": null,
    "goodsStoreId": null,
    "userId": null,
}


let requestParam = ref(JSON.parse(JSON.stringify(requestParamStart)));


let goodsStoreSelectSelect = (param: any) => {
    goodsStore.value = param;
    requestParam.value.goodsStoreId = param.id;
}

let isShowPasswordInput = ref(false);


/**
 * 打开弹窗
 */
let open = (param: any) => {
    roleCodes.value=[];

    if (param) {
        requestParam.value = JSON.parse(JSON.stringify(param));
        goodsStore.value=requestParam.value.goodsStore;
    }
    requestParam.value.goodsStoreId = goodsStore.value.id;

    if (requestParam.value.id == null || requestParam.value.id == '' ||
        requestParam.value.username == null || requestParam.value.username == '') {
        isShowPasswordInput.value = true;
    } else {
        isShowPasswordInput.value = false;
    }

    if(requestParam.value.userId!=null&&requestParam.value.userId!=""){
        // 获取用户角色
        $kt.request.request({
            url: '/system-user-web/user/getById',
            method: 'post',
            data: {
                id: requestParam.value.userId,
            },
        }).then((res) => {
            if (res.data.success) {
                roleCodes.value=res.data.data.roleCodes;
                console.log("获取用户角色成功",res.data.data);
                roleSelect.value.setRoleCodes(roleCodes.value);
                return false;
            }
            ElMessage({
                message: res.data.errMsg,
                type: 'error',
            });
        });
    }

    dialogVisible.value = true;
}

// 校验
let validate = () => {
    // 门店
    if (requestParam.value.goodsStoreId == null || requestParam.value.goodsStoreId == '') {
        ElMessage({
            message: '请选择门店',
            type: 'error',
        });
        return false;
    }

    if (requestParam.value.name == null || requestParam.value.name == '') {
        ElMessage({
            message: '请输入姓名',
            type: 'error',
        });
        return false;
    }

    if (requestParam.value.phone == null || requestParam.value.phone == '') {
        ElMessage({
            message: '请输入手机号',
            type: 'error',
        });
        return false;
    }

    // 身份证格式错误
    if (requestParam.value.idCard != null && requestParam.value.idCard != '') {
        if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(requestParam.value.idCard))) {
            ElMessage({
                message: '身份证格式错误',
                type: 'error',
            });
            return false;
        }
    }

    // 邮箱格式错误
    if (requestParam.value.email != null && requestParam.value.email != '') {
        if (!(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(requestParam.value.email))) {
            ElMessage({
                message: '邮箱格式错误',
                type: 'error',
            });
            return false;
        }
    }

    // 如果账号不为空，密码不能为空
    if (requestParam.value.username != null && requestParam.value.username != ""&&requestParam.value.userId==null) {
        if (requestParam.value.password == null || requestParam.value.password == "") {
            ElMessage({
                message: '请输入密码',
                type: 'error',
            });
            return false;
        }
    }

    return true;

}


let submit = async () => {

    if (!validate()) {
        return false;
    }

    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    // 是否继续执行
    let isContinue = true;

    if (requestParam.value.userId==null&&requestParam.value.username != null && requestParam.value.username != ""
        && requestParam.value.password != null && requestParam.value.password != "") {
        // 注册

        await $kt.request.request({
            url: '/system-user-web/user/register',
            method: 'post',
            data: requestParam.value,
        }).then((res) => {
            if (res.data.success) {
                console.log("注册成功",res.data);
                requestParam.value.userId = res.data.data.userInfo.id;
                return false;
            }
            loading.close();
            ElMessage({
                message: res.data.errMsg,
                type: 'error',
            });
            isContinue = false;
        });
    }

    if (!isContinue) {
        return false;
    }

    if(requestParam.value.userId!=null&&
    requestParam.value.userId!=""
    ){
        // 添加用户角色
        await $kt.request.request({
            url: '/system-user-web/user/setRole',
            method: 'post',
            data: {
                userId: requestParam.value.userId,
                roleCodes: roleCodes.value,
            },
        }).then((res) => {
            if (res.data.success) {
                console.log("添加用户角色成功",res.data);
                return false;
            }
            loading.close();
            ElMessage({
                message: res.data.errMsg,
                type: 'error',
            });
            isContinue = false;
        });
    }

    if (!isContinue) {
        return false;
    }

    $kt.request.request({
        url: '/business-goods-web/admin/emp/save',
        method: 'post',
        data: requestParam.value,
    }).then((res) => {
        if (res.data.success) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            dialogVisible.value = false;

            loading.close();
            // 提交
            emits('submit');
            dialogVisible.value = false;
            requestParam.value = JSON.parse(JSON.stringify(requestParamStart));
            goodsStore.value = {
                id: null,
                name: "所有门店",
            };

            return false;
        }
        loading.close();
        ElMessage({
            message: res.data.errMsg,
            type: 'error',
        });
    });

}






// 暴露给父组件的方法
defineExpose({
    open
})


</script>


<style lang="scss" scoped>
.img-uploaded {
    cursor: pointer;
}

.img-uploaded:hover {
    opacity: 0.8;
}
</style>